package com.zzyl.service.impl;

import cn.hutool.core.lang.hash.Hash;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.zzyl.service.WeChatService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;

@Service
public class WeChatServiceImpl implements WeChatService {
  private final String OPEN_ID_URL = "https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code";
  private final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";
  private final String PHONE_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";

  @Value("${zzyl.wechat.appid}")
  private String APP_ID;
  @Value("${zzyl.wechat.appsecret}")
  private String APP_SECRET;

  @Override
  public String getOpenId(String code) {
    Map mapInfo = getMapInfo();
    mapInfo.put("js_code",code);
    HttpResponse execute = HttpUtil.createRequest(Method.GET, OPEN_ID_URL).form(mapInfo).execute();
    JSONObject json = JSONUtil.parseObj(execute.body());
    if (json.getInt("errcode") != null) {
      throw new RuntimeException(json.getStr("errmsg"));
    }
    String openid = json.getStr("openid");
    return openid;
  }


  @Override
  public String getPhone(String detailCode) {
    String accessToken = getAccessToken();
    Map map = new HashMap();
    map.put("code", detailCode);
    // HttpResponse execute = HttpUtil.createRequest(Method.POST, PHONE_URL + accessToken).form("code", detailCode).execute();
    String result = HttpUtil.post(PHONE_URL + accessToken, JSONUtil.toJsonStr(map));
    JSONObject json = JSONUtil.parseObj(result);
    if (json.getInt("errcode") != 0) {
      throw new RuntimeException(json.getStr("errmsg"));
    }
    String phone = json.getJSONObject("phone_info").getStr("phoneNumber");
    return phone;
  }

  private String getAccessToken() {
    Map mapInfo = getMapInfo();
    HttpResponse execute = HttpUtil.createRequest(Method.GET, ACCESS_TOKEN_URL).form(mapInfo).execute();
    JSONObject json = JSONUtil.parseObj(execute.body());
    if (json.getInt("errcode") != null) {
      throw new RuntimeException(json.getStr("errmsg"));
    }
    String accessToken = json.getStr("access_token");
    return accessToken;
  }

  private Map getMapInfo() {
    Map map = new HashMap<>();
    map.put("appid", APP_ID);
    map.put("secret", APP_SECRET);
    return map;
  }
  public Map getWeChat() {
    Map map=new HashMap();
    map.put("appid",APP_ID);
    map.put("secret",APP_SECRET);
    return map;
  }
}
